<template>
  <div class="qa-detail-page">
    <!-- 头部 -->
    <div class="header d-flex align-items-center">
      <router-link to="/qa" class="text-dark">
        <i class="bi bi-chevron-left fs-4"></i>
      </router-link>
      <h5 class="mb-0 mx-auto">问题详情</h5>
    </div>

    <!-- 问题详情 -->
    <div class="qa-detail-container">
      <!-- 问题卡片 -->
      <div class="qa-card">
        <div class="qa-user-info">
          <img :src="question.avatar" alt="" class="qa-user-avatar">
          <div>
            <div class="fw-bold">{{ question.username }}</div>
            <div class="text-muted small">{{ question.userInfo }}</div>
          </div>
        </div>
        <div class="qa-content">
          {{ question.content }}
          <div v-if="question.image" class="qa-image">
            <img :src="question.image" alt="真题截图" class="img-fluid rounded">
          </div>
        </div>
      </div>

      <!-- 回答列表 -->
      <div v-for="answer in answers" :key="answer.id" 
           :class="['answer-card', answer.role]">
        <div class="d-flex align-items-center gap-2 mb-2">
          <i :class="getRoleIcon(answer.role)"></i>
          <span :class="['role-tag', answer.role]">{{ getRoleLabel(answer.role) }}</span>
          <span class="text-muted small">{{ answer.time }}</span>
        </div>
        <div class="answer-content" style="white-space: pre-wrap;" v-html="answer.content"></div>
        <div class="answer-actions mt-3">
          <button class="btn btn-sm btn-light me-2"
                  :class="{ active: answer.isLiked }"
                  @click="toggleLike(answer)">
            <i class="bi bi-hand-thumbs-up"></i>
            <span class="like-count">{{ answer.likes }}</span>
          </button>
          <button class="btn btn-sm btn-light" @click="toggleReply(answer)">
            <i class="bi bi-chat"></i>
            回复 <span class="reply-count">{{ answer.replies.length }}</span>
          </button>
        </div>
        <div class="reply-section" v-show="answer.showReplies">
          <div class="reply-list">
            <div v-for="reply in answer.replies" :key="reply.id" class="reply-item">
              <div class="d-flex align-items-center gap-2 mb-1">
                <span class="fw-bold">{{ reply.username }}</span>
                <span class="text-muted small">{{ reply.time }}</span>
              </div>
              <div>{{ reply.content }}</div>
            </div>
          </div>
          <div class="reply-input-wrapper">
            <input type="text"
                   class="form-control"
                   placeholder="写下你的回复..."
                   v-model="answer.newReply">
            <button class="btn btn-primary btn-sm"
                    @click="submitReply(answer)">发送</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 回答输入框 -->
    <div class="answer-input">
      <div class="input-wrapper">
        <textarea class="form-control"
                  :rows="textareaRows"
                  placeholder="写下你的回答..."
                  v-model="newAnswer"
                  @focus="expandInput"
                  @blur="collapseInput"></textarea>
        <i class="bi bi-send input-hint-icon"
           v-show="!newAnswer && textareaRows === 1"></i>
        <button class="send-btn"
                v-show="textareaRows > 1 || newAnswer"
                @click="submitAnswer">
          <i class="bi bi-send"></i>
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import http from "@/router/http";

export default {
  name: 'QaDetailView',
  data() {
    return {
      messageId: null,
      subjectId: null,
      currentReplyTargetId: null,
      textareaRows: 1,
      newAnswer: '',
      question: {
        id: 1,
        username: '张同学',
        userInfo: '2024考研 | 计算机专业',
        avatar: null,
        content: '2023年英语一真题Text 3中提到的"bleisure travel"具体是什么意思？为什么会出现这种旅行方式？',
        image: null
      },
      answers: []
    }
  },
  mounted() {
    this.messageId = this.$route.params.id;
    this.subjectId = this.$route.params.subjectId;
    this.fetchQuestions();
    this.fetchAnswers();
  },
  methods: {
    async fetchQuestions() {
      try {
        const response = await http.get(`/student/message/getMessageInfo?id=${this.messageId}`);
        const data = response.data.response;
        const baseUrl = http.defaults.baseURL || "";
        this.question.id = data.id;
        this.question.username = data.user.userName === null? "" : data.user.userName;
        this.question.userInfo = (data.user.userLevel === null? "" :data.user.userLevel) + "考研" + (data.user.targetMajor === null?"":data.user.targetMajor);
        this.question.avatar = baseUrl + "/uploadPath" + data.user.imagePath;
        this.question.content = data.publishContent === null ? "" : data.publishContent;
        if(data.contentImageAddress){
          this.question.image = baseUrl + "/uploadPath" + data.contentImageAddress;
        }
      } catch (error) {
        console.error('获取问题数据失败：', error);
      }
    },
    async fetchAnswers() {
      try {
        const response = await http.get(`/student/message/getReplyList?id=${this.messageId}`);
        this.answers = [];
        const data = response.data.response;
        data.forEach(item => {
          this.answers.push({
            id: item.messageId,
            role: item.status === 0 ? 'student' : item.status === 1 ? 'teacher' : item.status === 2 ? 'ai' : 'student',
            username: item.user.userName,
            time: item.timeStr,
            content: item.publishContent,
            answers: item.replyCount,
            likes: item.likes,
            isLiked: item.likesFlag === 1?true:false,
            showReplies: false,
            newReply: '',
            replies: item.replies.map(reply => {
              return {
                id: reply.id,
                username: reply.user.userName,
                time: reply.timeStr,
                content: reply.publishContent
              }
            })
          })
        })
      } catch (error) {
        console.error('获取问题数据失败：', error);
      }
    },
    getRoleIcon(role) {
      const icons = {
        ai: 'bi bi-robot',
        teacher: 'bi bi-mortarboard',
        senior: 'bi bi-person-check',
        student: 'bi bi-person'
      }
      return icons[role] || 'bi bi-person'
    },
    getRoleLabel(role) {
      const labels = {
        ai: 'AI助手',
        teacher: '老师',
        senior: '学长',
        student: '同学'
      }
      return labels[role] || '用户'
    },
    expandInput() {
      this.textareaRows = 3
    },
    collapseInput() {
      if (!this.newAnswer.trim()) {
        this.textareaRows = 1
      }
    },
    async toggleLike(answer) {
      answer.isLiked = !answer.isLiked
      answer.likes += answer.isLiked ? 1 : -1
      const flag = answer.isLiked ? 1 : 0
      await http.get("/student/messageLikesRecord/addOrCancelMessageLikesRecord?messageId="+answer.id+"&flag="+flag)
      .then(response => {
        if (response.status === 200) {
          console.log('点赞成功')
        } else {
          console.error('点赞失败，状态码：', response.status);
        }
      })
      .catch(error => {
         console.error('点赞失败：', error);
       })
    },
    toggleReply(answer) {
      // 关闭其他回复区域
      this.answers.forEach(a => {
        if (a !== answer) a.showReplies = false
      })
      answer.showReplies = !answer.showReplies
      this.currentReplyTargetId = answer.id;
    },
    async submitReply(answer) {
      if (!answer.newReply.trim()) return

      try {
        const requestInfo = {
          subject : this.$route.params.subjectId,
          content : answer.newReply,
          belongs :this.currentReplyTargetId,
          // file : this.impagePath
        }
        const response = await http.post('/student/message/addMessage', requestInfo);
        if (response.status === 200) {
          alert('回复提交成功');
          location.reload();
        } else {
          console.error('回复提交失败，状态码：', response.status);
          alert('回复提交失败，请检查网络连接或稍后重试');
        }
      } catch (error) {
        console.error('回复提交失败：', error);
        alert('回复提交出现异常，请检查网络连接或稍后重试');
      }
    },
    async submitAnswer() {
      if (!this.newAnswer.trim()) return
      try {
        const requestInfo = {
          subject : this.$route.params.subjectId,
          content : this.newAnswer,
          belongs : this.messageId
          // file : this.impagePath
        }
        const response = await http.post('/student/message/addMessage', requestInfo);
        if (response.status === 200) {
          alert('回答提交成功');
          location.reload();
        } else {
          console.error('回答提交失败，状态码：', response.status);
          alert('回答提交失败，请检查网络连接或稍后重试');
        }
      } catch (error) {
        console.error('回答提交失败：', error);
        alert('回答提交出现异常，请检查网络连接或稍后重试');
      }


    }
  }
}
</script>

<style scoped>
.qa-detail-page {
  background-color: #f0f9f9;
  padding-bottom: 60px;
}
.qa-detail-container {
  padding: 15px;
}
.qa-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.qa-user-info {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}
.qa-user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}
.answer-card {
  background: white;
  border-radius: 12px;
  padding: 15px;
  margin-bottom: 15px;
  border-left: 4px solid #eee;
}
.answer-card.ai { border-left-color: #00b8a9; }
.answer-card.teacher { border-left-color: #ff6b6b; }
.answer-card.senior { border-left-color: #4d96ff; }
.answer-card.student { border-left-color: #ffd93d; }

.role-tag {
  font-size: 0.9rem;
  padding: 2px 8px;
  border-radius: 12px;
  background: #f0f0f0;
}
.role-tag.ai {
  color: #00b8a9;
  background: #e6f7f6;
}
.role-tag.teacher {
  color: #ff6b6b;
  background: #ffe5e5;
}
.role-tag.senior {
  color: #4d96ff;
  background: #e6f0ff;
}
.role-tag.student {
  color: #ffa41b;
  background: #fff5e6;
}

.answer-content {
  margin: 15px 0;
  line-height: 1.6;
}
.answer-actions button {
  color: #666;
}
.answer-actions button.active {
  color: #00b8a9;
}
.reply-section {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}
.reply-item {
  padding: 10px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 10px;
}
.reply-input-wrapper {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}
.answer-input {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #f0f9f9;
  padding: 10px 0;
  z-index: 1000;
}
.input-wrapper {
  position: relative;
  background: white;
  padding: 15px;
  border-radius: 12px;
  margin: 0 15px;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.05);
}
.input-wrapper textarea {
  padding-right: 40px;
}
.input-hint-icon {
  position: absolute;
  right: 25px;
  top: 50%;
  transform: translateY(-50%);
  color: #ccc;
  pointer-events: none;
  transition: opacity 0.3s ease;
}
.send-btn {
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
  background: #00b8a9;
  color: white;
  border: none;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}
.send-btn:hover {
  background: #009e91;
  transform: translateY(-52%);
}
</style> 